import Vue from 'vue'
import Vuex from 'vuex'
import {
  ACCESS_TOKEN,
  USER_INFO
} from "@/common/util/constants"
import Chat from '@/socket/chat';
const chat = new Chat()
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // token
    token: '',
    // 用户信息
    userInfo: {},
    // 消息总数
    msgNum: 0,
    // 邀请总数
    invitationNum: 0,
    messageList: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    },

    SET_MSG_NUM: (state, msgNum) => {
      state.msgNum = msgNum
    },
    SET_INVITATION_NUM: (state, invitationNum) => {
      state.invitationNum = invitationNum
    },
    // 消息转发，通知各试图更新消息
    retransmission(state, res) {
      console.log('更新视图', res);
      if (res.constructor === Object) {
        const index = state.messageList.findIndex(item => item.update_time == res.update_time && res.userId == item
          .userId)
        if (index == -1) {
          state.messageList.push(res)
        }
      }
    }
  },
  actions: {
    // 登录
    mLogin({
      commit
    }, userInfo) {
      uni.setStorageSync(ACCESS_TOKEN, userInfo.token);
      uni.setStorageSync(USER_INFO, JSON.stringify(userInfo.userInfo));
      commit('SET_TOKEN', userInfo.token)
      commit('SET_USERINFO', userInfo.userInfo)
      // 登陆成功后，建立ws连接
      // chat.setup();
    },
    // 登出
    mLogout({
      commit,
      state
    }) {
      return new Promise(() => {
        commit('SET_TOKEN', '')
        uni.removeStorageSync(ACCESS_TOKEN)
        uni.removeStorageSync(USER_INFO)
      })
    },
    sendMessage({
      commit
    }, userInfo) {
      // console.log(userInfo, 'userInfos');
      chat.sendMessage(userInfo)
    },
    // 消息总数
    mMsgNum({
      commit
    }, msgNum) {
      commit('SET_MSG_NUM', msgNum)
    },
    // 邀请总数
    mInvitationNum({
      commit
    }, invitationNum) {
      commit('SET_INVITATION_NUM', invitationNum)
    },

  },
  getters: {
    token: state => {
      state.token = uni.getStorageSync(ACCESS_TOKEN);
      return state.token
    },
    userInfo: state => {
      state.userInfo = JSON.parse(uni.getStorageSync(USER_INFO));
      return state.userInfo
    },
    msgNum: state => {
      return state.msgNum
    },
    invitationNum: state => {
      return state.invitationNum
    },
  }
})
